package exquery

import org.apache.log4j.Logger
import exquery.valuebeans.export.SpeciesVO
import exquery.util.FormatResultUtil
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import exquery.util.ExportExperimentUtil

class SpeciesController {
    Logger gLogger = Logger.getLogger(SpeciesController.class)
    def speciesService
    def classSampleService
    def experimentClassService
    def experimentService
    def exportService
    def searchService

    FormatResultUtil formatResultUtil = new FormatResultUtil()

    def index = {
        redirect( controller:"search" ,params:[cmbSearchBy:"Species",searchText:"*"],action:"search")
    }

    def datalist={
      gLogger.info 'coming into action:datalist of controller:species'
      gLogger.info "params :: ${params}"
      def speciesName = params.speciesName
      def lookupBy = params.lookupBy
      def title="Result List By Species"
      def isExport = false
      if(params?.format && params.format != "html"){
        isExport = true
      }
      SpeciesVO speciesVO = speciesService.getSXSpeciesBySpeciesName(speciesName)
      def resultData = null

        if(lookupBy!=null && lookupBy.toString().trim().equalsIgnoreCase("experiments")){
             title="Experiment List By Species '${speciesName}'"
             def classIds = speciesService.getClassIdsBySpeciesName(speciesName)
             def result = experimentService.getExperimentsByClassIds(classIds)
             resultData = FormatResultUtil.getInstance().prepareExperimentsResult(result,params,isExport)

             if( result == null || result.size()==0 ){
                resultData.putAt "ErrorMsg","No Recoed Found"
             }else{
                resultData?.putAt "TotalRecordCount",result.size()
                resultData?.putAt "isExport",true
             }

          }else if(lookupBy!=null && lookupBy.toString().trim().equalsIgnoreCase("classes")){
             title="Class List By Species '${speciesName}'"
             def classIds = speciesService.getClassIdsBySpeciesName(speciesName)
             def result = experimentClassService.getClassesByClassIds(classIds)
             resultData = FormatResultUtil.getInstance().prepareClassesResult(result,params,isExport)

             if( result == null || result.size()==0 ){
                resultData.putAt "ErrorMsg","No Recoed Found"
             }else{
                resultData?.putAt "TotalRecordCount",result.size()
                resultData?.putAt "isExport",true
             }


          }else if(lookupBy!=null && lookupBy.toString().trim().equalsIgnoreCase("samples")){
             title="Sample List By Species '${speciesName}'"
             def samplesIds = speciesService.getSampleIdsBySpeciesName(speciesName)
             def result = classSampleService.getSamplesBySamplesIds(samplesIds)


             resultData = FormatResultUtil.getInstance().prepareSamplesResult(result,params,isExport)

             if( result == null || result.size()==0 ){
                resultData.putAt "ErrorMsg","No Recoed Found"
             }else{
                resultData?.putAt "TotalRecordCount",result.size()
                resultData?.putAt "isExport",true
             }
          }

        // Export Result
        if(params?.format && params.format != "html"){
          response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
          response.setHeader("Content-disposition", "attachment; filename=${lookupBy}LookUpBySpeciesResult.${params.extension}")
          if(resultData?.parameters?.title!=null){
            resultData?.parameters?.title = title
          }
          exportService.export(params.format, response.outputStream, resultData.resultList, resultData.fieldList, resultData.labelMap, resultData.formatters, resultData.parameters)
        }

      gLogger.info 'out from action:datalist of controller:species'
      return ["speciesName":speciesName,"lookupBy":lookupBy,"title":title,"speciesInfo":speciesVO,"result": resultData]
    }

    def exportexp={
      gLogger.info 'coming into action:exportexp of controller:species'
      gLogger.info "params :: ${params}"
      def speciesName = params.speciesName

      def classIds = speciesService.getClassIdsBySpeciesName(speciesName)
      def result = experimentService.getExperimentsByClassIds(classIds)
      gLogger.info "result :: ${result}"

      def workBook = ExportExperimentUtil.getInstance().exportExperiment(result)
      gLogger.info "workBook :: ${workBook}"

      // Export Result
      if(params?.format && params.format != "html"){
        String fileName = speciesName.toString().replace(" ","_")

        response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
        response.setHeader("Content-disposition", "attachment; filename=ExperimentsWithSpecies_${fileName}.${params.extension}")

        File temp = File.createTempFile("${speciesName}", ".${params.extension}");
        temp.deleteOnExit();

        // The Output file is where the xls will be created
        FileOutputStream fOut = new FileOutputStream(temp);
        // Write the XL sheet
        workBook.write(fOut);
        fOut.flush();
        // Done Deal..
        fOut.close();

        response.outputStream << temp.getBytes()
        response.outputStream.flush()
      }
      gLogger.info 'out from action:exportexp of controller:species'
      return
    }

    def list={
      //set lookup params
      params.put("cmbSearchBy","Species")
      params.put("searchText","*")


      def searchBy = params.cmbSearchBy
      def searchText = params.searchText

      // Export Result
      def resultData = []
      if(params?.format && params.format != "html"){
          response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
          response.setHeader("Content-disposition", "attachment; filename=${searchBy}List.${params.extension}")
          resultData = processSearch(searchBy,searchText,params,true)

          if(resultData?.parameters?.title!=null){
              resultData?.parameters?.title = "Species List"
          }

          exportService.export(params.format, response.outputStream, resultData.resultList, resultData.fieldList, resultData.labelMap, resultData.formatters, resultData.parameters)
      }else{

          resultData = processSearch(searchBy,searchText,params)
    }


    return [result: resultData]
  }


  private def processSearch(def searchBy,def searchText, def params = [:],boolean isExport = false){
    //call the service to search the data
      def resultSearch = searchService.search(searchBy, searchText, params)

      Collection<Map<?, ?>> result = resultSearch?.result
      def resultData = null
      resultData = FormatResultUtil.getInstance()."prepare${searchBy}Result"(result,params,isExport)

      if( resultSearch?.ErrorMsg != null ){
        resultData.putAt "ErrorMsg",resultSearch?.ErrorMsg
      }

      resultData?.putAt "isPaginate",resultSearch?.isPaginate
      resultData?.putAt "TotalRecordCount",resultSearch?.TotalRecordCount
      resultData?.putAt "isExport",resultSearch?.isExport

      return resultData
  }

}
